$(document).ready(function(){
    $("#search_term").keyup(function(){
        doSearch();
    });
    $("#search_cat").change(function(){
        doSearch();
    });
    
    addFancybox('#create_button');
    
    doSearch();
    
});

function doSearch(){
    $("#search_results").html("");
        
    var search_term = $("#search_term").val();
    var search_cat = $("#search_cat").val();

    $.post(getBaseURL()+"meal_editing/edit_ingredients/searchResults/", 
        {
            query: search_term,
            basetype: search_cat
        },
        function(data){
            $("#search_results").html(data);
        }
    ); 
}

function registerButtons(){
    
    addFancybox("#edit_ingredient");
    
    $("#delete_ingredient").click(function(e){
        e.preventDefault();
        if (confirm("This ingredient will be deleted from every meal that contains it. Are you sure you wish to delete it?")){
            $.post(getBaseURL()+"meal_editing/edit_ingredients/deleteIngredient",
                {ingredient_id: $("#ingr_id").attr('value')},
                function(data){
                    if (data == "good"){
                        location.reload();
                    }
                    else{ 
                        alert(data);
                    }
                }
            );
        }
    });
}

function selectIngredient(elem, id){
    $('#search_results .listItem').removeClass('selected');
    $(elem).addClass('selected');
    $.post(getBaseURL()+"meal_editing/edit_ingredients/previewIngredient/", 
        {ingredient_id: ""+id+""},
        function(data){
            $("#preview_ingredient").html(data);
            registerButtons();

        }
    );
}

function changeMadeReload(){
    location.reload();
}